from PyQt5.QtWidgets import (
    QWidget,
    QHBoxLayout,
    QLabel,
    QMenu,
    QAction,
    QMessageBox,
    QApplication,
)
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import os


class ThumbnailItemWidget(QWidget):
    def __init__(self, image_path, parent=None):
        super().__init__(parent)
        self.image_path = image_path

        layout = QHBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)

        self.thumbnail_label = QLabel()
        self.thumbnail_label.setFixedSize(120, 120)
        self.thumbnail_label.setAlignment(Qt.AlignCenter)

        pixmap = QPixmap(image_path)
        scaled_pixmap = pixmap.scaled(
            120, 120, Qt.KeepAspectRatio, Qt.SmoothTransformation
        )
        self.thumbnail_label.setPixmap(scaled_pixmap)

        self.path_label = QLabel(os.path.basename(image_path))
        self.path_label.setWordWrap(True)
        self.path_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.path_label.setToolTip(image_path)
        self.path_label.setTextInteractionFlags(Qt.TextSelectableByMouse)

        layout.addWidget(self.thumbnail_label)
        layout.addWidget(self.path_label, 1)
        self.setLayout(layout)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)

    def show_context_menu(self, position):
        menu = QMenu(self)
        copy_action = QAction("复制路径", self)
        copy_action.triggered.connect(self.copy_path)
        menu.addAction(copy_action)
        menu.exec_(self.mapToGlobal(position))

    def copy_path(self):
        clipboard = QApplication.clipboard()
        clipboard.setText(self.image_path)
        QMessageBox.information(self, "成功", "文件路径已复制到剪贴板")
